package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHSWUtil
import cn.com.kh.KHUtil
import com.alibaba.fastjson.JSON
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONObject

import java.text.SimpleDateFormat

/**
 *
 * @Title: api_SZWaterA00013DB
 * * @Description: 功能介绍：定时调用此接口，将水量波动短信documentout_ucis中符合条件的短信调度短信平台接口
 * @author: chieh* @date 2021-12-06 15:28:00
 *
 */

public class auto_SZWaterA00013DB implements EliteThreadInvoke {
    private static final Log log = LogFactory.getLog(auto_SZWaterA00013DB.class);

    public int doCallBack(EliteBean eliteBean, String content) {

        try {
            def SMSCount = 0;//累计数
            def message, msg;
            String outdata = "";
            String sms_guid = "";
            String documentout_guid = "";
            String documentpath = "";
            String documentto = "";
            String expectedstartdate = "";//短信入参
            def busdept = "";//短信发送类型
            def ext1 = "";//短信计划批次名称
            def docuciscount = 0;//短信数量

            log.debug("待处理名单线程Guid：" + content);

            // 获取短信批次的ID
            sms_guid = content;
            log.debug("获取短信批次的ID-sms_guid：" + sms_guid);

            // 检查是否是可以发送的时间
            if (KHSWUtil.isSendSMSTime(eliteBean, sms_guid)) {
                //查询当前催缴批次 在系统内是否有待发送的短信
                List selectdocucisList = eliteBean.chaxun_sql("select top 1000 documentout_guid,REPLACE(REPLACE(REPLACE(Documentpath,'【深圳水务集团】',''),'【','[') ,'】',']')as Documentpath,documentto,CONVERT(varchar(100), expectedstartdate, 20) as expectedstartdate from DOCUMENTOUT_UCIS where status =8 and doctype='3' and stringfield1='A00013' and sms_guid='" + sms_guid + "' and GETDATE()>ExpectedStartDate and ISNUMERIC(documentto)=1  and resultCode is null", "dataSource");
                docuciscount = selectdocucisList.size();
                log.debug("待发送催缴短信数量docuciscount：" + docuciscount);
                //判断如短信数量大于0则执行
                if (docuciscount > 0) {
                    //监控更新短信发送开始时间
                    eliteBean.update("Update Ucis_Sms_Monitoring Set Sendsms_Starttime = Getdate() Where Sms_Guid = '" + sms_guid + "' And Sendsms_Starttime Is Null", "dataSource");
                    //获取短信部门
                    def selectbusdeptresult = eliteBean.chaxun_sql("select top 1 b.sms_type as busdept,a.SMS_NAME as ext1 from Ucis_Smssendplan a left join ucis_deptcode b on a.DEPTCODE=b.DEPTCODE  where a.REC_GUID='" + sms_guid + "'", "dataSource");
                    if (selectbusdeptresult.size() > 0) {
                        busdept = selectbusdeptresult.get(0).get("busdept");
                        ext1 = selectbusdeptresult.get(0).get("ext1");
                    }
                    log.debug("发送短信类型busdept：" + busdept);
                    //循环执行发送
                    for (int j = 0; j < docuciscount; j++) {
                        Map selectdocucisMap = selectdocucisList.get(j);
                        documentout_guid = selectdocucisMap.get("documentout_guid");
                        documentpath = selectdocucisMap.get("documentpath");
                        documentto = selectdocucisMap.get("documentto");

                        String userMsgId = "BSMS_" + KHUtil.getRandomString(15);
                        outdata = sendsms(eliteBean, documentout_guid, documentto, documentpath, "水量波动通知", busdept, userMsgId, "", ext1);
                        log.debug("outdata：" + outdata);
                        //解析返回信息
                        JSONObject jsonObject = new JSONObject(outdata);
                        String statusCode = KHUtil.GetJV(jsonObject, "statusCode");
                        String resultMsg = KHUtil.GetJV(jsonObject, "resultMsg");
                        String resultCode = KHUtil.GetJV(jsonObject, "resultCode");
                        log.debug("statusCode：" + statusCode);
                        //成功提交
                        if (statusCode == "0") {
                            SMSCount++;
                            String updateDocumentoutSQL = "Update Documentout_Ucis Set Status = 3, Trialcount = Isnull(Trialcount, 0) + 1, Modifiedby = 'SENTTO', Modifieddate = Getdate(), Resultcode = '" + resultCode + "', userMsgId = '" + userMsgId + "', Send_Code = '" + statusCode + "', Send_Msg = '" + resultMsg + "', Send_Time = Getdate() Where Documentout_Guid = '" + documentout_guid + "'";

                            int updateDocumentouFlag = eliteBean.update(updateDocumentoutSQL, "dataSource");
                            log.debug("写入短信平台接口成功-短信平台回写DOCUMENTOUT_UCIS表SQL执行结果:" + updateDocumentouFlag);
                            //提交有返回，但是属于非成功的
                        } else {
                            String updateDocumentoutSQL = "Update Documentout_Ucis Set Status = Case When Isnull(Trialcount, 0) + 1 >= Isnull(Trialcountlimit, 3) Then '-1' Else Status End, SmsStatus = Case When Isnull(Trialcount, 0) + 1 >= Isnull(Trialcountlimit, 3) Then 'SMSFAIL' Else Null End, Trialcount = Isnull(Trialcount, 0) + 1, Modifiedby = 'SENTTO', Modifieddate = Getdate(), Send_Code = '" + statusCode + "', Send_Msg = '" + resultMsg + "', Send_Time = Getdate(), Resultcode = Case When Isnull(Trialcount, 0) + 1 >= Isnull(Trialcountlimit, 3) Then '" + userMsgId + "' Else Resultcode End, userMsgId = '" + userMsgId + "' Where Documentout_Guid = '" + documentout_guid + "' ";

                            int updateDocumentouFlag = eliteBean.update(updateDocumentoutSQL, "dataSource");
                            log.debug("写入短信平台接口失败-短信平台回写DOCUMENTOUT_UCIS表SQL执行结果:" + updateDocumentouFlag);
                        }
                    }
                    msg = "批次：" + sms_guid + " ,符合条件短信有" + docuciscount + "条数据，成功插入" + SMSCount + "条！";
                    log.debug("当前需要发送短信的数据处理结果:" + msg);
                } else {
                    log.debug("当前批次：" + sms_guid + " ,待发送催缴短信数量为0！");
                }
            } else {
                log.debug("当前批次：" + sms_guid + " ,不满足发送时间要求暂停发送(免打扰时间)！");
            }

            //2.开始处理短信发送后续事宜
            def selectremaincountresult = eliteBean.chaxun_sql("select COUNT(*) as remaincount from DOCUMENTOUT_UCIS where status!=3 and status!=-1 and doctype='3' and stringfield1='A00013' and  sms_guid='" + sms_guid + "' and ISNUMERIC(documentto)=1", "dataSource");
            def remaincount = selectremaincountresult.get(0).get("remaincount");
            log.debug("检查待发送催缴短信数量remaincount：" + remaincount);
            //查询待发送的为0 则默认已发送完成
            if (remaincount == 0) {
                //def selectsendcountresult = eliteBean.chaxun_sql("select count(*) as sendcount from DOCUMENTOUT_UCIS where 1=1 and status=3 and sms_guid='" + sms_guid + "'", "dataSource");
                def selectsendcountresult = eliteBean.chaxun_sql("select count(*) as sendcount,isnull(sum(case when resultCode is not null then 1 else 0 end),0) as resultcount from DOCUMENTOUT_UCIS where 1=1 and (status=3 or status=-1) and sms_guid='" + sms_guid + "'", "dataSource");
                def sendcount = selectsendcountresult.get(0).get("sendcount");
                def resultcount = selectsendcountresult.get(0).get("resultcount");
                log.debug("检查发送提交的催缴短信数量sendcount：" + sendcount + "	,需捞取的短信结果数量resultcount：" + resultcount);

                //获取拆分数据级 分小批次的数量级别  注意 此项 只能为数字 初始默认是2W
                def ucisdxcountresult = eliteBean.chaxun_sql("SELECT PARAMETERVALUE FROM SYSC_PARAMETER WHERE PARAMETER_ID = 'UCISDX'", "dataSource");
                def pageSize = ucisdxcountresult.get(0).get("PARAMETERVALUE");
                log.debug("pageSize :" + pageSize);

                double number = resultcount * 1.0 / Integer.parseInt(pageSize);
                log.debug("number :" + number);
                //提交缓存次数取整
                int count = Math.ceil(number);
                log.debug("count :" + count);
                int yscount = resultcount % Integer.parseInt(pageSize);
                log.debug("yscount :" + yscount);

                def topcount = 0;//结果更新的top数量
                //判断data长度,根据实际情况重置申明
                if (count == 1 && yscount > 0) {
                    topcount = yscount;//少于1次 或有余取余数
                } else {
                    topcount = pageSize;//判断入大于1 或刚好整数则先取默认拆分数
                }

                for (int i = 0; i < count; i++) {
                    String Result_guid = UUID.randomUUID().toString();
                    log.debug("Result_guid :" + Result_guid);
                    eliteBean.update("update top(" + topcount + ") DOCUMENTOUT_UCIS set Result_guid='" + Result_guid + "' where SMS_GUID='" + sms_guid + "' and Result_guid is null", "dataSource")
                    //判断data长度,根据实际情况重置申明
                    if (count == i + 1 && yscount > 0) {
                        topcount = yscount;//有余取余数
                    } else {
                        topcount = pageSize;//先取默认拆分数
                    }
                }

                //--催缴数据记录
                String[] data = new String[2];
                data[0] = "update ucis_sms_monitoring set sendsms_sum='" + sendcount + "',sendsms_endtime=GETDATE() where SMS_GUID='" + sms_guid + "'";
                data[1] = "update UCIS_CJ_result set sms_count='" + sendcount + "' where cj_guid='" + sms_guid + "'";
                log.debug("更新监控 处理SQL:" + data.toString());
                int[] dataresult = eliteBean.updateBatch(data, "dataSource");
                log.debug("更新监控 处理SQL结果:" + dataresult.toString());

                //--通知短信
                String starttime = "";
                String smscontent = "";
                def selectstarttimeresult = eliteBean.chaxun_sql("select CONVERT(varchar(100), sendsms_starttime, 20) as starttime from ucis_sms_monitoring where SMS_GUID='" + sms_guid + "'", "dataSource");
                if (selectstarttimeresult.size() > 0) {
                    starttime = selectstarttimeresult.get(0).get("starttime");
                }
                log.debug("催缴短信监控 开始发送时间starttime：" + starttime);

                def selectsmscontentresult = eliteBean.chaxun_sql("select sms_name+':共发送短信'+CONVERT(varchar(10),'" + sendcount + "')+'条，短信发送开始时间为'+CONVERT(varchar(30),'" + starttime + "',120) as smscontent  from ucis_smssendplan where type_id='A00013' and rec_guid='" + sms_guid + "'", "dataSource");
                if (selectsmscontentresult.size() > 0) {
                    smscontent = selectsmscontentresult.get(0).get("smscontent");
                }
                log.debug("催缴短信监控 通知短信内容smscontent：" + smscontent);
                //记录通知短信内容
                eliteBean.update("insert into ucis_sms_notice values('" + sms_guid + "','" + smscontent + "',GETDATE())", "dataSource")

                //查询需要通知的人员
                String phone;
                List selectphoneList = eliteBean.chaxun_sql("select phone from sms_book", "dataSource");
                def phonecount = selectphoneList.size();
                log.debug("短信通知管理人员的数量phonecount：" + phonecount);
                //判断如短信数量大于0则执行
                String temp = "";
                if (phonecount > 0 && smscontent != '' && smscontent != null) {
                    for (int m = 0; m < phonecount; m++) {
                        Map selectphoneMap = selectphoneList.get(m);
                        phone = selectphoneMap.get("phone");
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                        def expectedtime = df.format(new Date());
                        log.debug("短信通知发送时间:" + expectedtime)// new Date()为获取当前系统时间
                        String userMsgId = KHUtil.getRandomString(20);
                        outdata = KHSWUtil.sendSWSms(eliteBean, "", phone, smscontent, "SMS_JT", "系统报警", userMsgId, "");
                        log.debug("outdata：" + outdata);
                    }
                }
                //--流程表
                String[] data2 = new String[2];
                //data2[0] = "insert into ucis_sms_send select dateadd(minute,sms_jssc,getdate()),'A00013','" + sms_guid + "' from ucis_smssendplan where type_id='A00013' and rec_guid='" + sms_guid + "'";
                data2[0] = "insert into ucis_sms_send select dateadd(minute,10,getdate()),'A00013','" + sms_guid + "' from ucis_smssendplan where type_id='A00013' and rec_guid='" + sms_guid + "'";
                data2[1] = "delete from ucis_sms_smsfetch where TYPE_ID='A00013' and sms_guid='" + sms_guid + "'";
                //--短信拆分统计流程
                //data2[2]  = "insert into UCIS_SMS_Split values('"+sms_guid+"','UCIS水量波动',GETDATE()+3)";
                log.debug("最终批次处理SQL:" + data2.toString());
                int[] dataresult2 = eliteBean.updateBatch(data2, "dataSource");
                log.debug("最终批次处理SQL结果:" + dataresult2.toString());

            } else {
                log.debug("当前水量波动批次：" + sms_guid + " ,待发送催缴短信还有" + remaincount + "条！");
            }

        } catch (Exception e) {
            log.error("api_SZWaterDB异常信息：", e);
        }
        return 1;
    }

    //短信发送接口
    public static String sendsms(EliteBean eliteBean, String Documentout_Guid, String mobile, String content, String businessType, String loginName, String userMsgId, String extInfo, String batchName) {

        net.sf.json.JSONObject sendResultJson = KHSWUtil.sendSWSms(eliteBean, Documentout_Guid, mobile, content, loginName, businessType, userMsgId, extInfo, batchName);

        String statusCode = sendResultJson.has("code") ? sendResultJson.getString("code") : "-1";
        String resultMsg = sendResultJson.has("msg") ? sendResultJson.getString("msg") : "";
        String resultCode = sendResultJson.has("msgId") ? sendResultJson.getString("msgId") : "";

        JSONObject resultJson = new JSONObject();
        resultJson.put("statusCode", statusCode);
        resultJson.put("resultMsg", resultMsg);
        resultJson.put("resultCode", resultCode);

        return resultJson.toString();
    }
}